package com.vinxin.app.boss.feign.config

import cn.hutool.core.util.StrUtil
import cn.hutool.json.JSONUtil
import com.alibaba.fastjson2.JSONPath
import com.vinxin.app.exception.ResponseCodeEnum
import com.vinxin.app.exception.VXException
import feign.Response
import feign.Util
import feign.codec.Decoder
import java.lang.reflect.Type

class BossFeignDecoder : Decoder {
    override fun decode(response: Response?, type: Type?): String {
        val bodyText = Util.toString(response?.body()?.asReader(Util.UTF_8))
        if (StrUtil.isNotBlank(bodyText)
            && (JSONUtil.isTypeJSON(bodyText)
                    && StrUtil.equalsIgnoreCase("Success", JSONPath.eval(bodyText, "$.message") as String))
        ) {
            return JSONUtil.toJsonStr(JSONPath.eval(bodyText, "$.zpData"))
        } else {
            throw VXException(
                ResponseCodeEnum.CROSS_SERVER_ERROR,
                StrUtil.format("HTTP request failed and error message is [{}].", JSONPath.eval(bodyText, "$.message") as String)
            )
        }
    }
}